package com.abiao.shop.util;

import com.alibaba.fastjson.JSON;

/**
 * @Description: TurnUtil   字符串与bean转换工具类
 * @Author: AB
 * @Date: 2021-07-21
 * @Version:v1.0
 */
public class TurnUtil {
    /**
     * 把javaBean转化成字符串
     * @param value
     * @return
     */
    public static  <T>  String beanToString(T value){
        if (value == null){
            return null;
        }
        Class<?> clazz = value.getClass();  //利用java反射获取value的class
        if (clazz == Integer.class){
            return ""+value;
        }else if (clazz == String.class){
            return (String) value;
        }else if (clazz == Long.class){
            return ""+value;
        }else {
            return JSON.toJSONString(value);
        }
    }
    /**
     * 把字符串转化成javaBean
     * @param string
     * @return
     */
    public static  <T> T stringToBean(String string, Class<T> clazz){
        if (string == null || string.length() <= 0 || clazz == null){
            return null;
        }
        if (clazz == Integer.class){
            return (T)Integer.valueOf(string);
        }else if (clazz == String.class){
            return (T)string;
        }else if (clazz == Long.class){
            return (T)Long.valueOf(string);
        }else {
            return JSON.toJavaObject(JSON.parseObject(string),clazz);
        }
    }
}
